package org.example.api;

import org.apache.commons.codec.digest.DigestUtils;
import org.example.dao.ImageDao;
import org.example.model.ImageInfo;
import org.example.util.WebUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/image")
@MultipartConfig
public class ImageServlet extends HttpServlet {

    public static final String LOCAL_PATH_PREFIX = "/root/apache-tomcat-8.5.81/webapps/java_image_server/img";
    // 图片上传接口
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //请求数据：uploadImage=图片数据
        Part p = req.getPart("uploadImage");
        // TODO 先验证MD5值,如果存在就说明重复
        String md5 = DigestUtils.md5Hex(p.getInputStream());
        ImageInfo imageInfo = ImageDao.selectByMd5(md5);
        if(imageInfo != null) {
            //图片重复
            Map<String,Object> data = new HashMap<>();
            data.put("ok",false);
            data.put("msg","上传图片重复");
            WebUtil.serialize(resp,data);
            return;
        }
        // 1.保存在服务端本地硬盘:完整路径为路径前缀+后缀（自己约定）
        p.write(LOCAL_PATH_PREFIX + "/" + md5);
        // 2.保存在数据库
        ImageInfo image = new ImageInfo();
        image.setImageName(p.getSubmittedFileName());
        image.setSize(p.getSize());
        image.setUploadTime(new Date());
        image.setMd5(md5);
        image.setContentType(p.getContentType());
        image.setPath("/"+md5);
        // 插入操作
        int n = ImageDao.insert(image);
        // 返回响应
        Map<String,Object> data = new HashMap<>();
        data.put("ok",true);
        WebUtil.serialize(resp,data);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取图片列表接口
        List<ImageInfo> images = ImageDao.selectAll();
        WebUtil.serialize(resp, images);
    }

    @Override
    protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 1. 获取请求数据：获取图片id
        String imageId = req.getParameter("imageId");
        Integer id = Integer.parseInt(imageId);
        // 2. 删除本地文件（先根据图片id查询到图片，拼接完整路径再删除）
        ImageInfo imageInfo = ImageDao.selectOne(id);
        String path = LOCAL_PATH_PREFIX + imageInfo.getPath();
        File pic = new File(path);
        pic.delete();
        // 3. 删除数据库图片数据
        int n = ImageDao.delete(id);
        Map<String,Object> data = new HashMap<>();
        data.put("ok",true);
        WebUtil.serialize(resp,data);

    }
}
